<template>
  <el-dialog
    :destroy-on-close="true"
    :title="formData.id ? '编辑部门' : '新增部门'"
    :visible="showDialog"
    @close="btnCancel"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @blur="checkManager"
        >
          <el-option
            v-for="user in employeeList"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import {
  getDepartments,
  addDepartment,
  getDepartmentDetail,
  updateDepartment,
} from "../../../api/departments";
import { getEmployeeSimple } from "../../../api/employees";
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    nodedata: {
      type: Object,
      required: true,
    },
  },
  data() {
    const checkRepeatName = async (rule, val, callback) => {
      const { depts } = await getDepartments();

      let isRepeat;
      if (this.formData.id) {
        //通过id判断是新增还是编辑
        //编辑情况下 通过pid判断是否是在同级部门中有与自己相同的部门
        //并且编辑时修改的部门名称通过id来判断是否是存在的是自己
        isRepeat = depts
          .filter((item) => item.pid === this.nodedata.pid)
          .some((item) => item.name === val && item.id != this.nodedata.id);
      } else {
        isRepeat = depts
          .filter((item) => item.pid === this.nodedata.id)
          .some((item) => item.name === val);
      }
      isRepeat ? callback(new Error("同一个父部门下不能重名")) : callback();
    };
    const checkRepeatCode = async (rule, val, callback) => {
      // 1. 拿全部部门数据
      const { depts } = await getDepartments();
      // 2. 如果任何一个的 code 跟 val 则重复了
      let isRepeat;
      if (this.formData.id) {
        isRepeat = depts.some(
          (item) => item.code === val && item.id != this.nodedata.id
        );
      } else {
        isRepeat = depts.some((item) => item.code === val);
      }
      isRepeat ? callback(new Error("部门编码必须唯一")) : callback();
    };
    return {
      formData: {
        code: "",
        name: "",
        manager: "",
        introduce: "",
        pid: "",
      },
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            max: 50,
            message: "部门名称要求1-50个字符",
            trigger: "blur",
          },
          { validator: checkRepeatName, trigger: "blur" },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            max: 50,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          { validator: checkRepeatCode, trigger: "blur" },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            trigger: "blur",
            max: 300,
            message: "部门介绍要求1-50个字符",
          },
        ],
      },
      employeeList: [],
    };
  },
  async created() {
    this.employeeList = await getEmployeeSimple();
  },
  methods: {
    checkManager() {
      setTimeout(() => {
        this.$refs.addDept.validateField("manager");
      }, 100);
    },
    async btnOK() {
      //校验表单
      await this.$refs.addDept.validate();
      //通过判断id是否是新增还是编辑
      if (this.formData.id) {
        //发送编辑请求
        await updateDepartment(this.formData);
      } else {
        //发送新增请求
        await addDepartment({
          ...this.formData,
          pid: this.nodedata.id,
        });
      }
      //提示用户新增成功
      this.$message.success("操作成功");
      //重新获取页面数据更新页面
      this.$emit("addDepartment");
      //通知父组件关闭弹窗
      this.$emit("update:showDialog", false);
    },
    btnCancel() {
      // resetFields不能完全清空数据 回显的额外数据需要手动清空
      this.formData = {
        code: "",
        name: "",
        manager: "",
        introduce: "",
        pid: "",
      };
      this.$refs.addDept.resetFields();
      this.$emit("update:showDialog", false);
    },
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id);
    },
  },
};
</script>

<style>
</style>